//用户个人设置：交易密码/实名认证
app.controller('PayController', function($scope, $http, $q, $state, $ionicHistory,$ionicLoading, $ionicPopover, $ionicModal, $location, $stateParams, userService, payService, $ionicPopup, $httpParamSerializer) {
  //前提已经登录
  userService.getUserInfo(window.localStorage.memberId).then(function(result){
    if(result.code=='0'){
      //$scope.isauth = result.member.isAuth=='1'?false:true;
      $scope.trdata.iscard = result.member.isCard=='0'?false:true;
      $scope.istradepwd = result.member.isTradePwd=='0'?false:true;//?todo 设置本地持久存储
    }
  },function(){
    console.log('get userinfo error');    
  });
  
  $scope.payDatas = payService.get();
  //console.log($scope.payDatas);
  $scope.trdata ={};
  $scope.trdata.memberId = window.localStorage.memberId;
  $scope.trdata.ProductId = $stateParams.id;
  $scope.trdata.discountId = $scope.payDatas.discountId;
  $scope.trdata.TradeAmount = $scope.payDatas.TradeAmount;
  $scope.trdata.requiredAmount = $scope.payDatas.requiredAmount;
  //$scope.trdata.moduleId = $scope.payDatas.moduleId;//?todo
  if($scope.payDatas.discountAmount==null){
  	$scope.trdata.discountAmount=0;
  } else {
  	$scope.trdata.discountAmount = $scope.payDatas.discountAmount; 
  }
  $scope.trdata.discountAmountDesc=$scope.payDatas.discountAmountDesc;

/*  $scope.$watch('trdata.bankName', function(newValue){
    $scope.trdata.bankName = newValue; console.log(newValue);
  }); */
  //$scope.trdata.paymentmethod = false;
  if($scope.payDatas.paymentmethod) { //如果选择了,使用选择的，没选择用默认的
    $scope.trdata.paymentmethod = true;//是否选择了银行卡
    $scope.trdata.MemberBankId = $scope.payDatas.MemberBankId;
    $scope.trdata.bankName = $scope.payDatas.bankName;// only display
    $scope.trdata.cardNumber = $scope.payDatas.cardNumber;// only display
    $scope.trdata.iscard = $scope.payDatas.iscard; //only display
  }

  $http({
    method:'get',
    url: window.localStorage.base_url+'/app/product/get?productId='+$stateParams.id
  }).success(function(data,status,headers,config){
    //console.log('get success...');
    $scope.product = data.product; //console.log($scope.product);
    $scope.title = $scope.product.name;
    $scope.trdata.productName = $scope.product.name;
    if($scope.product.finishPer > 100){
      $scope.product.finishPer =100; //大于100,超卖违规
    }
    $scope.pmin=true;
    if($scope.trdata.discountId && $scope.trdata.requiredAmount){ //如果优惠有最小购买要求
      $scope.trdata.requiredAmount > $scope.product.minTradeAmount ? $scope.pmin=false:'';
    }
  }).error(function(data,status,headers,config){
    console.log('product get error');  
  });

  $scope.cards = [];
  function getCardList(){
    var deferred = $q.defer();
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/card/getCardList?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token).success(function(req){
      $ionicLoading.hide();
      deferred.resolve(req);//执行成功
    }).error(function(res){
      $ionicLoading.hide();
      deferred.reject();//执行失败
      console.log(res);
    })
    return deferred.promise;
  }

  //默认银行卡  console.log($scope.trdata);
  getCardList().then(function(result){      
    if(result.code=='0'){
        $scope.cards=result.cards;   //console.log($scope.cards);//undefined
        //有默认使用默认    defaultCard ?todo
        //没有默认 使用第一张卡
      	if(!$scope.trdata.paymentmethod &&result.defaultCard!=null){
      	  $scope.trdata.paymentmethod = true;
          $scope.trdata.iscard = true;
          $scope.trdata.MemberBankId = result.defaultCard.id;;
          $scope.trdata.bankName = result.defaultCard.bankName;
          $scope.trdata.cardNumber = result.defaultCard.cardNumber;
      	} else if(!$scope.trdata.paymentmethod && $scope.cards.length>=1){
          $scope.trdata.paymentmethod = true;
          $scope.trdata.iscard = true;
          $scope.trdata.MemberBankId = $scope.cards[0].id;;
          $scope.trdata.bankName = $scope.cards[0].bankName;
          $scope.trdata.cardNumber = $scope.cards[0].cardNumber;  //console.log($scope.trdata);
        }
      }else{
        console.log(result);
        $ionicPopup.alert({title: result.msg, okText:'确定'});
      }
  },function(){
    console.log('cards get error');
  });
  //console.log($scope.trdata);//undefined
  //var cardss = getCardList();

  //选择代金券 
  $scope.voucher = function() {
    payService.set($scope.trdata);  //save Tradedatas
    console.log($scope.iscard);
    window.localStorage.voucher = 'backtopay';//设置后返回交易 ?todo
    $state.go('pay-voucher',{}); 
  }  

  //设置交易密码 
  $scope.settradepwd = function() {
    payService.set($scope.trdata);  //save Tradedatas
    window.localStorage.paysettradepwdback = 'paysettradepwdback';
    $state.go('user-set-trade-password',{}); //设置后返回交易 
  }
  //选择支付方式  
  $scope.payment = function() {
    payService.set($scope.trdata);  //save Tradedatas
    console.log($scope.trdata);
    if($scope.trdata.iscard){
      $state.go('payment',{id:$stateParams.id});    
    }else{
      $ionicPopup.confirm({
        title:'您还没有添加银行卡，<br>点击确定添加银行卡',
        cancelText:'取消',
        okText:'确定'
      }).then(function(res) {
        window.localStorage.paybankcardaddback ="paybankcardaddback";
        if(res)$state.go('bankcard-add',{});//设置后返回交易
      });
      return;
    }
  }

  $scope.tradePwd="";   
  $scope.num={"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":0,"k":".","l":"C"};  
  $scope.doInput=function(n){    
    if ($scope.pwdlenght == 6 && n!="C") return false;    
    if(n=="C"){//清除键  
      $scope.tradePwd= $scope.tradePwd.slice(0,-1);     
    }else {
      $scope.tradePwd=$scope.tradePwd+""+n; 
    } 
        
    $scope.pwdlenght = $scope.tradePwd.length; 
  };
  var currentInput;

  $ionicModal.fromTemplateUrl('templates/pay/numberkeyboard.html', {  
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {  
    $scope.modalNumberKeyboard = modal;  
  });
  $scope.showKeyBoard=function(t){    
    $scope.modalNumberKeyboard.show();  
    var emodal = document.getElementsByClassName('keyboard')[0];
    angular.element(emodal.parentNode.parentNode).addClass('numberkeyboard');
    currentInput=t;  
  };
  $scope.finishInput=function(){  
    eval('$scope.'+currentInput+'=$scope.tradePwd==""?"0":$scope.tradePwd;');  
    $scope.modalNumberKeyboard.hide();  
  }


  $scope.agree = true;
  $scope.payable = true;
  $scope.agreec = function(){ console.log(1);
    $scope.agree = true;
    $scope.payable = true;
  };
  $scope.disagree = function(){console.log(0);
    $scope.agree = false;
    $scope.payable = false;
  };

  $scope.agreement = function(id){
    //$scope.modelagreement.show();
    $state.go('pay-agreement',{id:$stateParams.id});
  };


  //输交易密码 之前check
  $scope.pay = function() {
    payService.set($scope.trdata);  //save Tradedatas
    if(!$scope.payable){
      return;
    }
    if(typeof($scope.trdata.TradeAmount) == "undefined"){
      $ionicPopup.alert({
        title:'请填写您要购买的金额',
        okText:'确定'
      });
      return;
    }
    //交易金额 小于 起存金额
    if($scope.trdata.TradeAmount < $scope.product.minTradeAmount){
      $ionicPopup.alert({title:'存入金额不能小于起存金额',okText:'确定'});
      return;
    }
    //交易金额 大于 剩余金额
    if($scope.trdata.TradeAmount > $scope.product.remainingAmount){
      $ionicPopup.alert({title:'存入金额不能大于剩余金额',okText:'确定'});
      return;
    }
    //选择使用优惠 要求判断最少购买金额requiredAmount    
    if($scope.trdata.discountId && ($scope.trdata.TradeAmount < $scope.trdata.requiredAmount)){
      $ionicPopup.alert({title:'使用优惠最少存入金额为'+$scope.trdata.requiredAmount,okText:'确定'});
      return;
    }
    if(!$scope.trdata.iscard){
      $ionicPopup.confirm({
        title:'您还没有添加银行卡，<br>点击确定添加银行卡',
        cancelText:'取消',
        okText:'确定'
      }).then(function(res) {
        window.localStorage.paybankcardaddback ="paybankcardaddback";
        if(res)$state.go('bankcard-add',{}); //设置后返回交易  
      });
      return; 
    }

    //获取支付方式
    if(!($scope.trdata.MemberBankId)){
      payService.set($scope.trdata);
      $ionicPopup.confirm({
        title:'请选择支付方式',
        cancelText:'取消',
        okText:'确定'
      }).then(function(res) {
        if(res)$state.go('payment',{id:$stateParams.id});       
      });
      return;
    }
    if(!$scope.istradepwd){
      $ionicPopup.confirm({
        title:'您还没有设置交易密码，<br>点击确定设置交易密码',
        cancelText:'取消',
        okText:'确定'
      }).then(function(res) {
        window.localStorage.paysettradepwdback = 'paysettradepwdback';
        if(res)$state.go('user-set-trade-password',{}); //设置后返回交易  
      });
      return; 
    }        
    if(!$scope.agree){
      $ionicPopup.confirm({
        title:'是否同意《服务协议》',
        cancelText:'否',
        okText:'是'
      }).then(function(res) {
        if(res){
          $scope.agree =true;
          $scope.payable =true;
        }
        return true; 
      });
      return false; 
    }


    $scope.popuptwd = $ionicPopup.show({
      templateUrl: 'tradepwd.html',
      scope: $scope,
      cssClass: 'tradepwd'
    });/*,
      buttons: [
        { text: '取消' },
        {
          text: '确定',
          type: 'button-positive',
          onTap: function(e) {
            console.log(e);
          }
        }
      ]*/        

    $scope.popuptwd.then(function(res) {
     console.log('Tapped!', res);
    });
    $scope.showKeyBoard();

  };// input tradePwd

  $scope.shownumberkeyboard = function(){
    $scope.showKeyBoard();
  };
  $scope.canceltwd = function(){
    $scope.popuptwd.close();
    $scope.modalNumberKeyboard.hide(); 
  };
  $scope.$on('$destroy', function() {
    $scope.modalNumberKeyboard.remove();//对应删除      
  });

/*
  $scope.paytoverify = function(){
    $scope.trdata.tradePwd = $scope.tradePwd;
    $scope.trdata.TradeAmount = $scope.trdata.TradeAmount - 1; //voucher
    console.log($scope.trdata);
    //submitTradePwd  POST
    //memberId ProductId MemberBankId TradeAmount tradePwd
    $http.post(window.localStorage.base_url+'/app/trade/submitTradePwd?'+$httpParamSerializer($scope.trdata)+'&token='+window.localStorage.token)
      .success(function(req){
        if(req.code=='0'){
          console.log(req);          
          $scope.trdata.tradeInfo = req.tradeInfo;
          payService.set($scope.trdata);
          $scope.tradePwd="";
          $scope.pwdlenght = 0;
          $scope.popuptwd.close();
          $scope.modalNumberKeyboard.hide();
          $location.path('/pay/bankverify');          
        }else{
          console.log(req);
          $scope.tradePwd=""; 
          $scope.pwdlenght = 0;
          $scope.popuptwd.close();
          $scope.modalNumberKeyboard.hide();         
          $ionicPopup.alert({title: req.msg, okText:'确定'});
        }
      }).error(function(res){
        console.log(res);
      });
  };//paytoverify end*/

  $scope.orderdata ={};
  $scope.orderdata.memberId = window.localStorage.memberId;
  $scope.orderdata.ProductId = $stateParams.id;
  //$scope.vocher ?todo

  //memberId ProductId MemberBankId TradeAmount tradePwd //phone validateCode
  $scope.placeOrder = function(){
    payService.set($scope.trdata);  //save Tradedatas
    $scope.orderdata.MemberBankId = $scope.trdata.MemberBankId;
    $scope.orderdata.tradePwd = $scope.tradePwd; 
    $scope.orderdata.TradeAmount = $scope.trdata.TradeAmount;
    $scope.orderdata.discountId = $scope.trdata.discountId;
    $scope.orderdata.discountAmount = $scope.trdata.discountAmount;
    console.log($scope.orderdata);
    $ionicLoading.show();
    $http.post(window.localStorage.base_url+'/app/trade/submitTrade?'+$httpParamSerializer($scope.orderdata)+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req); 
        //$scope.trdata.tradeInfo = req.tradeInfo;
        //交易密码错误五次锁定?todo
        $scope.tradePwd="";
        $scope.pwdlenght = 0;
        $scope.popuptwd.close();
        $scope.modalNumberKeyboard.hide();
        $state.go('order-index',{}); //订单支付完 赠送?todo
        //数据 TradeResp req.productName,ta:req.tradeAmount,bn:req.bankName,cn:req.cardName
      }else{
        console.log(req);
        $scope.tradePwd="";
        $scope.pwdlenght = 0;
        $scope.popuptwd.close();
        $scope.modalNumberKeyboard.hide();
        $ionicPopup.alert({title: req.msg, okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  };

})

.controller('agreementController', function($scope, $http, $q, $state, $ionicHistory, $ionicLoading,$location, $stateParams, userService, payService, $ionicPopup, $httpParamSerializer) {
  //$status.protocol="<b>1</b>";  
  $http({
    method:'get',
    url: window.localStorage.base_url+'/app/config/payAgreement?productId='+$stateParams.id
  }).success(function(data,status,headers,config){
    console.log(data);
    //$scope.protocol = data.payAgreement;
    angular.element(document.getElementById("protocolDiv")).html(data.payAgreement);
  }).error(function(data,status,headers,config){
    console.log('product get error');  
  });
})
.controller('PayVoucherController', function($scope, $http, $q, $state, $ionicHistory, $ionicLoading,$location, $stateParams, userService, payService, $ionicPopup, $httpParamSerializer) {
  $scope.discounts = [];
  function getVoucherList(){
    var deferred = $q.defer();
    var url = window.localStorage.base_url+'/app/discount/getMyDiscounts?memberId='+window.localStorage.memberId+'&state=0&moduleId=0&token='+window.localStorage.token;
    $ionicLoading.show();
    $http.get(url).success(function(req){
      $ionicLoading.hide();
      deferred.resolve(req);//执行成功 console.log(url);      
    }).error(function(res){
      $ionicLoading.hide();
      deferred.reject();//执行失败
      console.log(res);
    })
    return deferred.promise;
  }

  getVoucherList().then(function(result){      
    if(result.code=='0'){
        $scope.discounts=result.discounts;   console.log($scope.discounts);//undefined
      }else{
        console.log(result);
        $ionicPopup.alert({title: result.msg, okText:'确定'});
      }
  },function(){
    console.log('Discounts get error');
  });

  $scope.payData = {};
  $scope.payDatas = payService.get();
  $scope.payData = $scope.payDatas;
  //console.log($scope.payData);
  $scope.select = function(discount){
    if(discount==null){
      $scope.payData.discountId = ''; 
      $scope.payData.discountAmount = 0;
      $scope.payData.discountType = 0;
      $scope.payData.discountAmountDesc = '';
  	} else {
      $scope.payData.discountId = discount.id;//discount.id不能显示选择 
      $scope.payData.requiredAmount = discount.requiredAmount;
      if(discount.type==1){
      	$scope.payData.discountAmountDesc="投资金,"+discount.amount+"元";
      } else if(discount.type==2){
      	$scope.payData.discountAmountDesc="加息券,"+discount.interestPercent+"%";
      } else if(discount.type==3){
      	$scope.payData.discountAmountDesc="代金券,"+discount.amount+"元";
      }
      if(discount.type==3){
      	$scope.payData.discountAmount = discount.amount;
      } else {
      	$scope.payData.discountAmount = 0;
      }
      /*angular.forEach($scope.discounts,function(value){ 
        if(value.discountId==id){
          $scope.payData.discountAmount = value.amount;
        }
      }); */          
    }
    payService.set($scope.payData);
    $ionicHistory.goBack();
  }
})

.controller('PaymentController', function($scope, $http, $state, $location, $ionicLoading, $ionicHistory, payService, $stateParams, $ionicPopup, $httpParamSerializer) {

  $scope.cards=[];
  function getCardList(){
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.get(window.localStorage.base_url+'/app/card/getCardList?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token).success(function(req){
      $ionicLoading.hide(); 
      if(req.code=='0'){
        $scope.cards = req.cards;
        angular.forEach($scope.cards,function(value,key){          
          value.bankPingyin = eval('banklist.'+value.bankName); //增加银行对应拼音
          if (value.bankPingyin){
            value.bankpng = 'img/bank/'+value.bankPingyin+'.png';
          }else{
            value.bankpng = 'img/bank/undefined.png';
          }
        });        
        console.log($scope.cards);
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg, okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide(); 
      console.log(res);
    })
  }
  getCardList();
  $scope.add_bankcard = function() {
    window.localStorage.paybankcardaddback = "paybankcardaddback";
    $location.path('/bankcard/add');
  };
  $scope.card={
    cardNumber:'',
    bankName:'',
    realname:'',
    phoneNumber:'',
    memberId:window.localStorage.memberId
  };
  $scope.trdata = payService.get();
  console.log($scope.trdata)
  $scope.trdata.paychoice = $scope.trdata.MemberBankId;
  $scope.backPayment = function(id,name,no) {
    $scope.trdata.paymentmethod = true;
    $scope.trdata.MemberBankId = id;
    $scope.trdata.bankName = name;
    $scope.trdata.cardNumber = no;
    payService.set($scope.trdata);
    $ionicHistory.goBack();
  } 
})

.controller('OrderController', function($scope, $location, $stateParams, payService) {
  $scope.orderdata = payService.get();//支付成功 payService数据清空?todo
  console.log($stateParams);
  console.log($scope.orderdata);
})

/*
.controller('PayBankverifyController', function($scope, $http, $state, $location, $ionicHistory, $timeout, payService, $stateParams, $ionicPopup, $httpParamSerializer) {
  $scope.PayBankverifyDatas = payService.get();
  console.log($scope.PayBankverifyDatas);

  $scope.productName = $scope.PayBankverifyDatas.tradeInfo.productName;
  $scope.TradeAmount = $scope.PayBankverifyDatas.TradeAmount;
  $scope.bankName = $scope.PayBankverifyDatas.tradeInfo.bankName;
  $scope.cardNo = $scope.PayBankverifyDatas.tradeInfo.cardNo;
  $scope.name = $scope.PayBankverifyDatas.tradeInfo.name;
  $scope.idNo = $scope.PayBankverifyDatas.tradeInfo.idNo;

  $scope.verifydata = {};
  $scope.verifydata.phone = $scope.PayBankverifyDatas.tradeInfo.phone;

  var inf='';
  function checkphone(){
    if(!$scope.verifydata.phone){
      inf='请填写手机号';
      return;
    }
    if(!/^1\d{10}$/.exec($scope.verifydata.phone)){
      inf='请检查手机号输入格式';
      return false;
    }
    return true;
  }


  if(/^1\d{10}$/.test($scope.PayBankverifyDatas.tradeInfo.phone)){
    $scope.fetchButton=false;
  }else{
    $scope.fetchButton=true;
  }  
  $scope.isValidPhone = function(){
    if(/^1\d{10}$/.test($scope.verifydata.phone)){
      $scope.fetchButton=false;
    }else{
      $scope.fetchButton=true;
    }
  };
  
  $scope.getVerifyCode = function(){
    if(checkphone()){
      settime();
      $http.get(window.localStorage.base_url+'/app/trade/getVerifyCode?phone='+$scope.verifydata.phone+'&memberId='+$scope.PayBankverifyDatas.memberId+'&memberBankId='+$scope.PayBankverifyDatas.MemberBankId+'&token='+window.localStorage.token)
      .success(function(req){
        if(req.code=='0'){
          console.log(req);        
        }else{
          console.log(req);
          if(timer!=null){//失败了重置短信
            $timeout.cancel(timer);
            $scope.fetchButton=false;
            $scope.buttonText="获取"; 
            countdown = 60; 
          }
          $ionicPopup.alert({title: req.msg,okText:'确定'});
        }
      }).error(function(res){
        console.log(res);
      });
    }else{
      $ionicPopup.alert({title: inf, okText:'确定'});
    }
  }

  $scope.buttonText="获取";
  var countdown=60;  
  var timer;
  function settime() { 
    if (countdown == 0) { 
      $scope.fetchButton=false;
      $scope.buttonText="获取"; 
      countdown = 60; 
    } else { 
      $scope.fetchButton=true;
      $scope.buttonText="重试(" + countdown + ")";
      countdown--; 
      timer = $timeout(function() { 
        settime();
      },1000) 
    } 
  }

  $scope.orderdata = {};
  $scope.orderdata.memberId = $scope.PayBankverifyDatas.memberId;
  $scope.orderdata.ProductId = $scope.PayBankverifyDatas.ProductId;
  $scope.orderdata.MemberBankId = $scope.PayBankverifyDatas.MemberBankId;
  $scope.orderdata.TradeAmount = $scope.PayBankverifyDatas.TradeAmount;
  $scope.orderdata.tradePwd = $scope.PayBankverifyDatas.tradePwd;

  function checknext(){
    if(!$scope.verifydata.phone){
      inf='请填写手机号';
      return;
    }
    if(!/^1\d{10}$/.exec($scope.verifydata.phone)){
      inf='请检查手机号输入格式';
      return false;
    }
    if(!/^\d{4}$/.test($scope.verifydata.validateCode)){
      inf='请填写4位数字验证码';
      return false;
    }
    return true;
  }
  
  $scope.placeOrder = function(){
    if(checknext()){
      $scope.orderdata.phone = $scope.verifydata.phone;
      $scope.orderdata.validateCode = $scope.verifydata.validateCode;
      console.log($scope.orderdata);
      $http.post(window.localStorage.base_url+'/app/trade/submitTrade?'+$httpParamSerializer($scope.orderdata)+'&token='+window.localStorage.token)
      .success(function(req){
        if(req.code=='0'){
          console.log(req); 
          $state.go('/oder/index',{}); 
          //数据 TradeResp req.productName,ta:req.tradeAmount,bn:req.bankName,cn:req.cardName
        }else{
          console.log(req);
          $ionicPopup.alert({title: req.msg, okText:'确定'});
        }
      }).error(function(res){
        console.log(res);
      });
    }else{
      $ionicPopup.alert({title: inf, okText:'确定'});
    }
  };
})
*/